// presentation/screen/DeviceDetailScreen.kt
package com.hwpt.chesedemo.presentation.screen

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Error
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.hwpt.chesedemo.presentation.viewmodel.DeviceDetailViewModel

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DeviceDetailScreen(
    navController: NavController,
    deviceAddress: String,
    deviceName: String
) {
    val viewModel: DeviceDetailViewModel = hiltViewModel()
    val state by viewModel.state.collectAsState()
    val scrollState = rememberScrollState()

    // 初始化设备信息
    LaunchedEffect(deviceAddress, deviceName) {
        if (state.deviceName.isEmpty()) {
            viewModel.initializeFromAddress(deviceAddress, deviceName)
        }
    }

    Scaffold(
        topBar = {
            CenterAlignedTopAppBar(
                title = {
                    Text(
                        text = "设备详情",
                        fontSize = 20.sp,
                        fontWeight = FontWeight.Bold
                    )
                },
                navigationIcon = {
                    IconButton(onClick = { navController.navigateUp() }) {
                        Icon(Icons.Default.ArrowBack, contentDescription = "返回")
                    }
                }
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(16.dp)
                .verticalScroll(scrollState),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            // 设备信息卡片
            Card(
                modifier = Modifier.fillMaxWidth()
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(12.dp),
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Text(
                        text = state.deviceName,
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold
                    )

                    Text(
                        text = state.deviceAddress,
                        fontSize = 14.sp,
                        color = Color.Gray
                    )
                }
            }

            // 错误消息显示
            state.errorMessage?.let { error ->
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    colors = CardDefaults.cardColors(
                        containerColor = Color(0xFFFFF2F2)
                    )
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(12.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            imageVector = Icons.Default.Error,
                            contentDescription = "错误",
                            tint = Color.Red,
                            modifier = Modifier.size(20.dp)
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text(
                            text = error,
                            fontSize = 12.sp,
                            color = Color.Red
                        )
                    }
                }
            }

            // 连接状态卡片
            Card(
                modifier = Modifier.fillMaxWidth()
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(12.dp),
                    verticalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        Column(
                            modifier = Modifier.weight(1f)
                        ) {
                            Text(
                                text = state.connectionStatus,
                                fontSize = 16.sp,
                                fontWeight = FontWeight.Medium
                            )

                            if (state.isConnected) {
                                Text(
                                    text = "连接成功",
                                    fontSize = 12.sp,
                                    color = Color.Green
                                )
                            }
                        }

                        Row(
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Checkbox(
                                checked = state.autoReconnect,
                                onCheckedChange = { viewModel.setAutoReconnect(it) },
                                modifier = Modifier.padding(start = 8.dp)
                            )

                            Text(
                                text = "自动重连",
                                fontSize = 12.sp,
                                modifier = Modifier.padding(start = 4.dp)
                            )
                        }
                    }

                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        Button(
                            onClick = { viewModel.connectDevice() },
                            modifier = Modifier.weight(1f),
                            enabled = !state.isConnected,
                            colors = ButtonDefaults.buttonColors(
                                containerColor = MaterialTheme.colorScheme.primary
                            )
                        ) {
                            Text("连接设备")
                        }

                        Button(
                            onClick = { viewModel.disconnectDevice() },
                            modifier = Modifier.weight(1f),
                            enabled = state.isConnected,
                            colors = ButtonDefaults.buttonColors(
                                containerColor = MaterialTheme.colorScheme.error
                            )
                        ) {
                            Text("断开连接")
                        }
                    }
                }
            }

            if (state.showMtuSection) {
                Card(
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Column(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(12.dp),
                        verticalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        Text(
                            text = "MTU设置",
                            fontSize = 14.sp,
                            fontWeight = FontWeight.Bold
                        )

                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(
                                text = "当前MTU: ",
                                fontSize = 14.sp
                            )

                            Text(
                                text = state.currentMtu.toString(),
                                fontSize = 14.sp,
                                fontWeight = FontWeight.Bold,
                                color = MaterialTheme.colorScheme.primary
                            )

                            Spacer(modifier = Modifier.weight(1f))

                            OutlinedTextField(
                                value = state.mtuInput,
                                onValueChange = { viewModel.setMtuInput(it) },
                                label = { Text("MTU值") },
                                placeholder = { Text("23-517") },
                                modifier = Modifier.width(100.dp),
                                singleLine = true
                            )

                            Button(
                                onClick = { viewModel.saveMtu() },
                                modifier = Modifier.padding(start = 8.dp)
                            ) {
                                Text("保存")
                            }
                        }

                        Text(
                            text = "注：MTU（Maximum Transmission Unit）是最大传输单元，影响数据传输效率",
                            fontSize = 10.sp,
                            color = Color.Gray
                        )
                    }
                }
            }

            if (state.showDataSection) {
                Card(
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Column(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(12.dp),
                        verticalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            verticalAlignment = Alignment.CenterVertically,
                            horizontalArrangement = Arrangement.SpaceBetween
                        ) {
                            Text(
                                text = "接收数据",
                                fontSize = 14.sp,
                                fontWeight = FontWeight.Bold
                            )

                            OutlinedButton(
                                onClick = { viewModel.clearReceivedData() }
                            ) {
                                Text("清空")
                            }
                        }

                        // 数据显示模式选择
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.Start,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(
                                text = "显示模式：",
                                fontSize = 12.sp
                            )

                            RadioButton(
                                selected = state.displayAsHex,
                                onClick = { viewModel.setDisplayMode(true) }
                            )
                            Text(
                                text = "HEX",
                                modifier = Modifier.padding(start = 4.dp),
                                fontSize = 12.sp
                            )

                            RadioButton(
                                selected = !state.displayAsHex,
                                onClick = { viewModel.setDisplayMode(false) },
                                modifier = Modifier.padding(start = 8.dp)
                            )
                            Text(
                                text = "ASCII",
                                modifier = Modifier.padding(start = 4.dp),
                                fontSize = 12.sp
                            )
                        }

                        // 数据接收框
                        Card(
                            modifier = Modifier
                                .fillMaxWidth()
                                .height(200.dp),
                            colors = CardDefaults.cardColors(
                                containerColor = Color(0xFFF5F5F5)
                            )
                        ) {
                            Box(
                                modifier = Modifier
                                    .fillMaxSize()
                                    .padding(8.dp)
                            ) {
                                if (state.receivedData.isNotEmpty()) {
                                    androidx.compose.foundation.text.BasicTextField(
                                        value = state.receivedData,
                                        onValueChange = {},
                                        textStyle = TextStyle(
                                            fontSize = 11.sp,
                                            fontFamily = FontFamily.Monospace,
                                            color = Color(0xFF333333)
                                        ),
                                        modifier = Modifier.fillMaxSize()
                                    )
                                } else {
                                    Text(
                                        text = "等待接收数据...",
                                        fontSize = 12.sp,
                                        fontFamily = FontFamily.Monospace,
                                        color = Color.Gray,
                                        modifier = Modifier.align(Alignment.Center)
                                    )
                                }
                            }
                        }

                        Text(
                            text = "发送数据",
                            fontSize = 14.sp,
                            fontWeight = FontWeight.Bold
                        )

                        // 发送模式选择
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.Start,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(
                                text = "发送模式：",
                                fontSize = 12.sp
                            )

                            RadioButton(
                                selected = state.sendAsHex,
                                onClick = { viewModel.setSendMode(true) }
                            )
                            Text(
                                text = "HEX",
                                modifier = Modifier.padding(start = 4.dp),
                                fontSize = 12.sp
                            )

                            RadioButton(
                                selected = !state.sendAsHex,
                                onClick = { viewModel.setSendMode(false) },
                                modifier = Modifier.padding(start = 8.dp)
                            )
                            Text(
                                text = "ASCII",
                                modifier = Modifier.padding(start = 4.dp),
                                fontSize = 12.sp
                            )
                        }

                        // 数据发送输入框
                        OutlinedTextField(
                            value = state.sendDataInput,
                            onValueChange = { viewModel.setSendDataInput(it) },
                            modifier = Modifier
                                .fillMaxWidth()
                                .height(60.dp),
                            placeholder = { Text("输入要发送的数据...") },
                            textStyle = TextStyle(
                                fontSize = 12.sp,
                                fontFamily = FontFamily.Monospace
                            )
                        )

                        // 发送按钮
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            verticalAlignment = Alignment.CenterVertically,
                            horizontalArrangement = Arrangement.End
                        ) {
                            Button(
                                onClick = { viewModel.sendData() },
                                enabled = state.sendDataInput.isNotEmpty()
                            ) {
                                Text("发送数据")
                            }
                        }
                    }
                }
            }
        }
    }
}